package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.domain.CompanyInfo;
import com.sanjishu.enterlab.electricity.sale.mapper.CompanyInfoMapper;
import com.sanjishu.enterlab.electricity.sale.utils.Page;
import com.sanjishu.enterlab.electricity.sale.utils.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CompanyManageService {

    @Autowired
    CompanyInfoMapper companyInfoMapper;
    @Value("${page.size}")
    private Integer pageSize;

    public Page<CompanyInfo> findNewCompanyByPage(Integer page) {
        Long count = companyInfoMapper.countNewCompany();
        if (count == 0) {
            return new Page<CompanyInfo>(new PageRequest(1, pageSize), new ArrayList<>(), count);
        }
        PageRequest request = new PageRequest(page, pageSize);
        List<CompanyInfo> result = companyInfoMapper.findNewCompanyByPage(request);
        Page<CompanyInfo> pageData = new Page<CompanyInfo>(request, result, count);
        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), pageSize);
            result = companyInfoMapper.findNewCompanyByPage(request);
            pageData = new Page<>(request, result, count);
        }
        return pageData;
    }
}
